package com.running.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.isomorphic.criteria.AdvancedCriteria;
import com.isomorphic.criteria.Criterion;
import com.isomorphic.criteria.DefaultOperators;
import com.isomorphic.criteria.criterion.SimpleCriterion;
import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.isomorphic.datasource.DataSource;
import com.isomorphic.datasource.DataSourceManager;

/**
 * 短信配额实现 
 * @author Administrator
 */
public class SmsTaskDMI {
	@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
	public DSResponse add(DSRequest request ,Map record)throws Exception
	{
		//判断已经发送数据是否是上月的,如果是短信彩信已发清零
		DataSource companyDS = DataSourceManager.getDataSource("companyDS");
		Map company = companyDS.fetchById(record.get("corp_sid_fk"));
		Date lastSentDate = (Date) company.get("lastSentDate");
		Date currentDate = new Date();
		if(lastSentDate!= null && 
				!(currentDate.getYear() == lastSentDate.getYear() && 	currentDate.getMonth() == lastSentDate.getMonth())
		){
			//更新已发彩信短信值为0
			Map values  = new HashMap();
			values.put("smSent", 0);
			values.put("mmSent", 0);
			DSRequest dr = new DSRequest("depDS","update");
			dr.setAllowMultiUpdate(true);
			dr.setCriteria("corp_sid",record.get("corp_sid_fk"));
			dr.setValues(values);
			dr.execute();
		}
		
		//判断是否启用配额
		List<Map> parents = getParents((String)record.get("corp_sid_fk"),(String)record.get("dept_sid_fk"));
		Boolean msLimit = (Boolean) company.get("ms_limit");
		if(msLimit != null && true == msLimit){
			//如果配额启用，判断所有上级部门短信是否达到配额,如果有一个达到,则不能发送
			 for(Map dep : parents){
				 Integer smSent  = (Integer) dep.get("smSent");
				 if(smSent == null) smSent = 0;
				 Integer smLimit  = (Integer) dep.get("smLimit");
				 if(smLimit != null && smLimit != -1 && smSent >= smLimit ){
					 throw new RuntimeException((String)record.get("mt_dst_num"));
				 }
			 }
		}
		DSResponse ds =  request.execute();//插入待发
		
		//更新上次发送时间
		Map values  = new HashMap();
		values.put("lastSentDate", new Date());
		companyDS.update(company, values);
		//更新已发数量
		 for(Map dep : parents){
			 Integer smSent  = (Integer) dep.get("smSent");
			 if(smSent == null) smSent = 0;
			 Map value = new HashMap();
			 value.put("smSent", smSent+1);
			 DSRequest dr = new DSRequest("depDS","update");
			 dr.setValues(value);
			 dr.setCriteria("pk", dep.get("pk"));
			 dr.execute();//增加发送数量
		 }
		 
		return ds;

	}

	/**
	 * 获得指定部门的所有父部门，包含自己
	 * @param companyPk
	 * @param depPk
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<Map> getParents(String companyPk, String depPk) throws Exception {
		DSRequest dr = new DSRequest("depDS","fetch");
		List<Criterion> criterions = new ArrayList<Criterion>();
		String pk = companyPk;
		criterions.add(new SimpleCriterion("pk", "equals", pk));
		while(!pk.equals(depPk)){
			pk = depPk.substring(0, pk.length()+3);
			criterions.add(new SimpleCriterion("pk", "equals", pk));
		}
		Criterion[] cs = new Criterion[criterions.size()];
		for(int i = 0; i<criterions.size(); i++){
			cs[i] = criterions.get(i);
		}
		 AdvancedCriteria criteria = new AdvancedCriteria(DefaultOperators.Or,  cs);
		dr.setCriteria(criteria);
		return dr.execute().getDataList();
	}


}
